package thanhlong90.it.testsocket;
import java.io.*;
import java.net.*;

class TCPChatServer {
	private final int POST = 4322;
	private boolean serverStatus = true;
	ServerSocket ss;
	Socket s;
	PrintWriter out;
	BufferedReader in, in2;
	
	public TCPChatServer() {
		
	}
	
	public void run() {
		try {
			this.ss = new ServerSocket(POST, 10);
			System.out.println("Server is listenning...");
			while (serverStatus) {
				this.s = ss.accept();
				System.out.print("Server has connected!\n");
				// Create input and output stream
				this.out = new PrintWriter(s.getOutputStream(), true);
				Reader reader = new InputStreamReader(s.getInputStream());
				this.in = new BufferedReader(reader);
				// Receive
				System.out.println("Đang chờ nhận dữ liệu từ client ... ");
				while (!in.ready()) {
					
				}
				/*BufferedReader kbin = new BufferedReader(new InputStreamReader(System.in));
				String kq3 = kbin.readLine();
				String kq4 = kbin.readLine();
				out.println(kq3 + kq4);*/
				
				String result = in.readLine();
				System.out.println("Đã lấy đc dữ liệu: " + result);
				out.println("Server đã nhận đc dữ liệu");
				
				if (result.equals("quit")){
					System.out.println("Server đã thực hiện dừng hoạt động! ");
					serverStatus = false;
				}
			}
			closeConnect();
		}
		catch (Exception e) {
			System.out.print("Error Khoi Tao Server\n");
		}
	}

	public void closeConnect(){
		try {
			// Close
			this.out.close();
			this.in.close();
			this.s.close();
			this.ss.close();
		} catch (IOException e) {
			System.out.print("Thực hiện close thất bại!");
			e.printStackTrace();			
		}
		
	}
	
	public static void main(String args[]) {
		TCPChatServer a = new TCPChatServer();
		a.run();
	}
}
